package com.scalar.chiptrack.operations.reports.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.operations.reports.dao.WipFlushDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.FileOutputStream;
import java.io.File;
import java.io.ByteArrayOutputStream;

/**
 * User: Sujan
 * Date: Aug 22, 2005
 * Time: 5:18:34 PM
 */
public class WipFlushExportToFileAction extends ChipTrackAction
{
    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute (SessionKeys.USER_KEY);
        ArrayList wipFlush = ( ArrayList )session.getAttribute ( "wipFlush" );
        HashMap errors  = new HashMap();
        if (user == null || wipFlush == null )
        {
            request.setAttribute ( "sessionExpired", Boolean.TRUE.toString() );
            return mapping.findForward ( "success" );
        }

        String reportType   = request.getParameter ( "reportType" );
        String heading      = request.getParameter ( "heading" );
        String holdHeading  = request.getParameter( "holdHeading" );
        String lotExpand    = request.getParameter("lotExpand" );
        String vendorExpand = request.getParameter("vendorExpand" );
        String productExpand = request.getParameter("productExpand" );
        Workbook workbook = null;
        String fileName = null;
        if ( "byProduct".equalsIgnoreCase( reportType ) )
        {
            try
            {
                //System.out.println("vendorExpand = " + vendorExpand + "" + lotExpand);
                workbook = WipFlushDAO.getWorkbookForWipFlushByProduct( wipFlush, heading, holdHeading, vendorExpand, lotExpand );
            }
            catch ( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        else if ( "byVendor".equalsIgnoreCase( reportType ) )
        {
            try
            {
                //System.out.println("byvendor productExpand = " + productExpand + "" + lotExpand);
                workbook = WipFlushDAO.getWorkbookForWipFlushByVendor( wipFlush, heading, holdHeading, productExpand, lotExpand );
            }
            catch( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        else if ( "byProductShippableWeek".equalsIgnoreCase( reportType ) )
        {
            int startingWWNumber = 0;
            try{
                startingWWNumber = Integer.parseInt ( request.getParameter("startingWWNumber"));
            }catch ( NumberFormatException e ){}
            int wwYear = 0;
            try{
                wwYear = Integer.parseInt ( request.getParameter("wwYear") );
            }catch ( NumberFormatException e ){}
            int noOfWeeks = 0;
            try{
                noOfWeeks = Integer.parseInt( request.getParameter("noOfWeeks") );
            }catch( NumberFormatException e ){}
            try
            {
                //System.out.println("byProductShippableWeek vendorExpand = " + vendorExpand + "" + lotExpand);
                workbook = WipFlushDAO.getWorkbookForWipFlushShippableByProductWeek ( wipFlush, heading, holdHeading, startingWWNumber, wwYear, noOfWeeks, vendorExpand, lotExpand );
            }
            catch( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        else if ( "byProductShippableMonth".equalsIgnoreCase( reportType ) )
        {
            try
            {
                //System.out.println("byProductShippableMonth vendorExpand = " + vendorExpand + "" + lotExpand);
                workbook = WipFlushDAO.getWorkbookForWipFlushShippableByProductMonth( wipFlush, heading, holdHeading, vendorExpand, lotExpand );
            }
            catch( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        else if ( "byVendorShippableWeek".equalsIgnoreCase( reportType ) )
        {
            int startingWWNumber = 0;
            try{
                startingWWNumber = Integer.parseInt ( request.getParameter("startingWWNumber"));
            }catch ( NumberFormatException e ){}
            int wwYear = 0;
            try{
                wwYear = Integer.parseInt ( request.getParameter("wwYear") );
            }catch ( NumberFormatException e ){}
            int noOfWeeks = 0;
            try{
                noOfWeeks = Integer.parseInt( request.getParameter("noOfWeeks") );
            }catch( NumberFormatException e ){}
            try
            {
                //System.out.println("byVendorShippableWeek productExpand = " + productExpand + "" + lotExpand);
                workbook = WipFlushDAO.getWorkbookForWipFlushShippableByVendorWeek( wipFlush, heading, holdHeading, startingWWNumber, wwYear, noOfWeeks, productExpand, lotExpand);
            }
            catch( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        else if ( "byVendorShippableMonth".equalsIgnoreCase( reportType ) )
        {
            try
            {
                workbook = WipFlushDAO.getWorkbookForWipFlushShippableByVendorMonth( wipFlush, heading, holdHeading, productExpand, lotExpand );
            }
            catch( Exception e )
            {
                errors.put ( "Could not Generate Excel File", null );
                e.printStackTrace();
            }
        }
        FileOutputStream fileOut;
        String filePath = null;
            filePath = request.getSession().getServletContext().getRealPath( ConfigManager.getWipFlushFilePath() );
            boolean exists = ( new File( filePath ) ).exists();
            if ( !exists )
            {
                File file = new File( filePath );
                file.mkdirs();
            }
            fileOut = new FileOutputStream( filePath + "/" + fileName );
            if ( workbook != null )
            {
                try
                {
                    workbook.write( fileOut );
                    fileName = "WipFlush.xls";
                    request.setAttribute ( "fileName", fileName );
                }
                catch ( Exception e )
                {
                    //errors.put ( "Could not write excel file to disk", null );
                    e.printStackTrace();
                }
            }
            fileOut.close();
        ExcelUtils.generateExcelReport( workbook, "WipFlush_"+ DateUtil.getTimeStamp(), response);
        return mapping.findForward ( "reportview" );
    }
}
